package com.cloud.salon.client.authority.service.impl;

import com.cloud.salon.client.authority.repository.RoleAuthorityRepository;
import com.cloud.salon.client.authority.service.*;
import com.cloud.salon.common.base.entity.authority.Authority;
import com.cloud.salon.common.base.entity.authority.Role;
import com.cloud.salon.common.base.entity.authority.relation.RoleAuthority;
import com.cloud.salon.common.base.response.Res;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description
 * @Author wolf--LZH
 * @CreateDate 2019/5/3 0003 下午 3:47
 */
@Service
public class RoleAuthorityServiceImpl implements RoleAuthorityService {

    @Autowired
    private RoleAuthorityRepository roleAuthorityRepository;
    @Autowired
    private RoleService roleService;
    @Autowired
    private AuthorityService authorityService;

    public Res setRoleAuthoritys(Integer roleId, List<Integer> authorityIdList) {
        // 获取要设置的用户实体, 若为空则返回错误信息
        Res<Role> roleRes = roleService.findById(roleId);
        if(roleRes.getData() == null)
            return new Res(-3, "无此角色");

        // 获取当前用户所具备的角色
        Res<List<Authority>> roleAuthorityRes = authorityService.findByRole(roleId);
        List<Authority> roleAuthorityList = roleAuthorityRes.getData();

        // 通过id列表获取要设置的角色列表
        Res<List<Authority>> authorityRes = authorityService.findByIdList(authorityIdList);
        List<Authority> authorityList = null;
        if(authorityRes.getData() == null)
            return new Res(-3, "获取要设置的权限列表失败,请确保参数正确");
        else
            authorityList = authorityRes.getData();

        // 添加当前用户不具备的角色
        for (Authority authority: authorityList) {
            if(!roleAuthorityList.contains(authority)) {
                // 新增实体
                RoleAuthority save = new RoleAuthority();
                save.setRoleId(roleId);
                save.setAuthorityId(authority.getId());

                roleAuthorityRepository.save(save);
            }
        }

        // 删除不在具备的角色
        for (Authority authority: roleAuthorityList) {
            if(!authorityList.contains(authority)) {
                // 删除该角色
                roleAuthorityRepository.deleteByRoleIdAndAndAuthorityId(roleId, authority.getId());
            }
        }

        return new Res(0, "操作成功");
    }
}
